package com.cirkana.viewer.profile;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.cirkana.CirkanaActivity;
import com.cirkana.serial.SerializationException;
import com.cirkana.viewer.R;

public class SignInActivity extends CirkanaActivity {

	public static final int RESULT_SIGNIN_OK = 0;

	private Button signinButton;
	private EditText userEditText;
	private EditText passwordEditText;

	private SignInPassData passData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signin);
		
		this.signinButton = ((Button) findViewById(R.id.login_signin));
		this.userEditText = ((EditText) findViewById(R.id.user));
		this.passwordEditText = ((EditText) findViewById(R.id.password));

		this.passData = (SignInPassData) getResult();
		if (this.passData.hasProfile()) {
			this.userEditText.setText(this.passData.getProfile()
					.getCirkanaCredential().getUser());
			this.passwordEditText.setText(this.passData.getProfile()
					.getCirkanaCredential().getPassword());
		}

		this.signinButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String user = userEditText.getText().toString();
				String password = passwordEditText.getText().toString();
				SignInPassData result = new SignInPassData();
				result.setProfile(new Profile(user, password));
				try {
					setResult(RESULT_SIGNIN_OK, result);
				} catch (SerializationException e) {
					showErrorMessage(e);
				}
				finish();
			}
		});

	}

	public static Intent createIntent(Context context, Profile profile)
			throws SerializationException {
		Intent intent = new Intent(context, SignInActivity.class);
		SignInPassData data = new SignInPassData();
		data.setProfile(profile);
		CirkanaActivity.setPassData(intent, data);
		return intent;
	}
}
